const path = require('path');
const Koa = require('koa');
const cors = require('@koa/cors'); 
const koaBody = require('koa-body');
const Router = require('koa-router');
const { pool } = require('./db/index'); 
const static = require('koa-static');
const svgCaptcha = require('svg-captcha');
const sessionModule = require('koa-session');

const session = sessionModule.createSession;

const app = new Koa();

// 配置 session
app.keys = ['some secret key'];
const CONFIG = {
  key: 'koa:sess', 
  maxAge: 86400000, 
  autoCommit: true, 
  overwrite: true, 
  httpOnly: true, 
  signed: true, 
  rolling: false, 
  renew: false, 
};
app.use(session(CONFIG, app));

// 处理跨域
app.use(cors({
    origin: ['http://localhost:3000'], // 允许前端地址
    credentials: true
}));

// 使用 koa-body 中间件处理文件上传
app.use(koaBody({
    multipart: true,
    formidable: {
        uploadDir: path.join(__dirname),
        maxFileSize: 200 * 1024 * 1024, 
        keepExtensions: true 
    },
    json: true, 
    text: true, 
    urlencoded: true 
}));

// 配置静态文件服务
app.use(static(__dirname, './img'));

// 引入首页路由
const homepageRouter = require('./routes/homepage/index');
const bookLibraryRouter = require('./routes/bookLibrary/index');
const calLibraryRouter = require('./routes/calLibrary/index');
const loginRouter = require('./routes/Login/index');
const friendcircleRouter = require('./routes/friendcircle/index');
app.use(homepageRouter.routes());
app.use(homepageRouter.allowedMethods());
app.use(bookLibraryRouter.routes());
app.use(bookLibraryRouter.allowedMethods());
app.use(calLibraryRouter.routes());
app.use(calLibraryRouter.allowedMethods());
app.use(loginRouter.routes());
app.use(loginRouter.allowedMethods());
app.use(friendcircleRouter.routes());
app.use(friendcircleRouter.allowedMethods());

const port = 3001;
const server = app.listen(port, () => {
    console.log(`Koa2 服务器运行在端口 ${port}`);
});

// 将 serverUrl 传递给路由模块
homepageRouter.serverUrl = 'http://localhost:3001';
bookLibraryRouter.serverUrl = 'http://localhost:3001';
friendcircleRouter.serverUrl = 'http://localhost:3001';
bookLibraryRouter.localUrl = "D:\\graduateProject\\koa2Graduate\\";
